package top.dimples.utils;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import top.dimples.common.Consts;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtil {
    public static final JWTSigner SIGNER = JWTSignerUtil.hs256(Consts.JWT_KEY.getBytes());

    /**
     * 生成jwt
     *
     * @param payload jwt 负载
     * @return jwt 字符串
     */
    public static String generateToken(Map<String, String> payload) {
        log.info("用户生成token");
        return Consts.BEARER + JWT.create()
                .setExpiresAt(new Date(System.currentTimeMillis() + 7 * 24 * 60 * 3600))
                .setSigner(SIGNER)
                .setPayload("info", payload).sign();
    }


    /**
     * 验证 token 是否有效
     *
     * @param token jwt
     * @return 是否有效
     */
    public static boolean validateToken(String token) {
        try {
            String jwt = token.split(Consts.BEARER)[1];
            JWTValidator.of(jwt).validateAlgorithm(SIGNER).validateDate(new Date());
            return true;
        } catch (Exception e) {
            log.info("token验证失败");
            return false;
        }
    }


    /**
     * @param token jwt
     * @return jwt 信息的 map
     */
    public static HashMap<String,String> parseToken(String token) throws IOException {
        String jwt = token.split(Consts.BEARER)[1];
        JWT parseToken = JWTUtil.parseToken(jwt);
        ObjectMapper objectMapper = new ObjectMapper();
        HashMap<String,String> hashMap = objectMapper.readValue(parseToken.getPayload("info").toString(), HashMap.class);
        return hashMap;

    }


}
